<template>
	<view class="cardBg">
		<uni-section :title="'设备：'+bindsInfo.name" type="line" style="padding: 6px 0;" />
		<view class="rect">
			<u--form labelWidth='70' labelPosition="left" :model="bindsInfo">
				<u-form-item label="协议">
					<u--input disabled disabledColor="#eee" v-model="bindsInfo.proto" border="none"></u--input>
				</u-form-item>
				<block v-if="bindsInfo.proto === 'modbus-rtu'">
					<u-form-item label="通讯地址">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.addr" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="波特率">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.baudrate" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="数据位">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.databits" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="奇偶校验">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.parity" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="停止位">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.stopbits" border="none">
						</u--input>
					</u-form-item>
				</block>
				<block v-else>
					<u-form-item label="设备IP">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.ip" border="none"></u--input>
					</u-form-item>
					<u-form-item label="子网掩码">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.mask" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="网关地址">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.gateway" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="默认端口">
						<u--input disabled disabledColor="#eee" v-model="bindsInfo.port" border="none">
						</u--input>
					</u-form-item>
				</block>
				<u-form-item label="网关编码">
					<u--input disabled disabledColor="#fff" v-model="bindsInfo.gateway" border="none"
						placeholder="请选择网关"></u--input>
					<u-icon slot="right" name="arrow-right" @click="showGateways = true"></u-icon>
				</u-form-item>
				<u-form-item label="网关端口">
					<u--input disabled disabledColor="#fff" v-model="bindsInfo.inface" border="none"
						placeholder="请选择端口"></u--input>
					<u-icon slot="right" name="arrow-right" @click="showInface = true"></u-icon>
				</u-form-item>
			</u--form>
			<view class="button">
				<u-button type="primary" text="确定" @click="handleBind()"></u-button>
			</view>
		</view>
		<u-action-sheet :show="showGateways" :actions="gatewaysOptions" title="请选择网关" @close="showGateways = false"
			@select="gatewaySelect">
		</u-action-sheet>
		<u-action-sheet :show="showInface" :actions="infaceOptions" title="请选择端口" @close="showInface = false"
			@select="infaceSelect">
		</u-action-sheet>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showGateways: false,
				showInface: false,
				gatewayInfo: {},
				gatewaysOptions: [],
				current: 0,
				bindsInfo: {},
				tplList: [],
				realInfo: [],
			};
		},
		watch: {},
		computed: {
			infaceOptions() {
				if (this.bindsInfo.proto === 'modbus-rtu') {
					return [{
							name: 'rs485a',
							_id: 'rs485a'
						},
						{
							name: 'rs485b',
							_id: 'rs485b'
						},
						{
							name: 'rs232',
							_id: 'rs232'
						},
					]
				} else {
					return [{
						name: 'lan',
						_id: 'lan'
					}]
				}
			},
			getCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			}
		},
		components: {

		},
		methods: {
			onBackPress(event) {
				console.log('event~~', event);
				uni.switchTab({
					url: '/pages/device/device',
				})
				return true;
			},
			gatewaySelect(e) {
				this.bindsInfo.gateway = e.name
				this.getGateways(e);
			},
			infaceSelect(e) {
				this.bindsInfo.inface = e.name
			},
			goBack() {
				uni.navigateBack()
			},
			tabsClick(e) {
				this.current = e.index;
				console.log('e', e);
			},
			async handleBind() {
				/*
				新增绑定设备页面，进入页面后判断设备是否绑定，没有绑定的情况下跳转绑定页面，绑定成功跳转
				**/
				const db = uniCloud.database()
				if (!this.bindsInfo.gateway) return uni.$u.toast('请选择网关名称')
				if (!this.bindsInfo.inface) return uni.$u.toast('请选择网关端口')
				let update = {}
				this.gatewayInfo.ports[this.bindsInfo.inface].enable = true
				if (this.bindsInfo.proto === 'modbus-rtu') {
					update.proto = this.bindsInfo.proto
					update.addr = this.bindsInfo.addr
					update.baudrate = this.bindsInfo.baudrate
					update.databits = this.bindsInfo.databits
					update.stopbits = this.bindsInfo.stopbits
				} else {
					update.proto = this.bindsInfo.proto
					update.ip = this.bindsInfo.ip
					update.mask = this.bindsInfo.mask
					update.gateway = this.bindsInfo.gateway
				}
				this.realInfo.ports[this.bindsInfo.inface].Device.push({
					"DeviceType": this.bindsInfo.template,
					"data": this.tplList,
				})
				this.realInfo.ports[this.bindsInfo.inface].enable = true
				// console.log('readData.ports[this.bindsInfo.inface]~~~', this.realInfo);
				// --------------实时数据配置--------------
				await db.collection("gateways").where({
					"name": this.bindsInfo.gateway,
					"category": "realtime"
				}).update({
					ports: this.realInfo.ports
				});

				this.gatewayInfo.ports[this.bindsInfo.inface].devices.push(update)
				uni.showLoading({
					title: '绑定中...'
				});
				// --------------网关配置--------------
				await db.collection("gateways").doc(this.gatewayInfo._id).update({
					ports: this.gatewayInfo.ports
				});
				// --------------设备信息更新--------------
				await db.collection("res").doc(this.bindsInfo._id).update({
					bindStatus: 1,
					mqttStatus: Math.floor(Math.random() * 2) == 1 ? 'Online' : 'Offline',
					linkstr: this.bindsInfo.proto === 'modbus-rtu' ?
						this.bindsInfo.gateway + '/' + this.bindsInfo.inface + '/' + this.bindsInfo.addr : this
						.bindsInfo.gateway + '/' + this.bindsInfo.inface

				});
				await uni.$u.toast('绑定成功')
				await uni.hideLoading();
				uni.switchTab({
					url: '/pages/device/device',
				})
			},

			async getGateways(e) {
				const db = uniCloud.database()
				let res = null
				if (!e) {
					res = await db.collection('gateways').where({
						category: 'sn'
					}).get()
					this.gatewaysOptions = res.result.data.map(item => {
						return {
							name: item.name,
							_id: item._id,
						}
					})
				} else {
					res = await db.collection('gateways').where({
						_id: e._id,
					}).get()
					this.gatewayInfo = res.result.data[0]
				}
			},
			async getTpl() {
				const db = uniCloud.database()
				const res = await db.collection('temp').where({
					_id: this.bindsInfo.templateId
				}).get()
				this.tplList = res.result.data[0].record
			},
			async getRead() {
				const db = uniCloud.database()
				const res = await db.collection('gateways').where({
					"name": this.bindsInfo.gateway,
					"category": "realtime"
				}).get()
				this.realInfo = res.result.data[0]
			},
		},
		onLoad: function(option) {
			this.bindsInfo = JSON.parse(decodeURIComponent(option.item));
			this.getGateways()
			this.getTpl()
			this.getRead()
		}
	}
</script>

<style lang="scss" scoped>
	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;

		.title {
			text-align: center;
			padding: 0 0px 10px;
			border-bottom: 1px solid #409eff;

			.iconleft {
				position: fixed;
				left: 30px;
			}
		}
	}



	::v-deep .u-cell__label {
		color: #409eff;
		font-size: 32rpx;
		font-weight: 600;
	}
	::v-deep .uni-input-input{
		margin-left: 10px !important;
	}
	.banner {
		.goBack {
			left: 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			position: fixed;
			z-index: 99;

			.icon {
				width: 27px;
				height: 27px;
				border-radius: 50px;
				line-height: 28px;
				background: rgba(0, 0, 0, 0.05);
				border: 2rpx solid rgba(255, 255, 255, 1);
				text-align: center;
			}

			.title {
				font-size: 14px;
				color: #fff;
				margin-left: 10px;
				font-weight: 700;
			}
		}

		width: 750rpx;
		// padding: 30rpx 0;

		swiper {
			width: 750rpx;
			height: 340rpx;

			&-item {
				width: 100%;
				height: 100%;
				// padding: 0 30rpx;

				image {
					width: 100%;
					height: 100%;
					// border-radius: 10rpx;
				}
			}
		}
	}

	.contbox {
		width: 345px;
		height: 44px;
		margin: 10px auto;
		border-radius: 16rpx;
		box-shadow: 0 0 14rpx rgba(0, 0, 0, 0.05);
		background: radial-gradient(117.67% 54.29% at 70.23255813953489% -0.8583690987124464%, rgba(217, 241, 255, 1) 0.01%, rgba(246, 252, 255, 1) 100%);
		border: 1px solid rgba(255, 255, 255, 1);
		// position: relative;
		// top: -40px;
		// left: 0;
	}
</style>